package com.hengtiansoft.lfy.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.hengtiansoft.lfy.entity.EvaluatorMessageEntity;
import com.hengtiansoft.lfy.entity.EvaluatorModeEntity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 评测数据库操作类
 */
public class EvaluatorDBManager {
    static private EvaluatorDBManager dbMgr = new EvaluatorDBManager();
    private EvaluatorDBHelper dbHelper;

    public void onInit(Context context) {
        dbHelper = EvaluatorDBHelper.getInstance(context);
    }

    public static synchronized EvaluatorDBManager getInstance() {
        return dbMgr;
    }

    /**
     * 删除模块信息
     */
    public synchronized  void deleteMode(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //先清除上次内容
        db.delete(EvaluatorDBHelper.MODE_TABLE_NAME,null,null);
    }
    /**
     * 保存模块信息
     * @param mode
     */
    public synchronized  boolean insertMode(List<EvaluatorModeEntity> mode){
        if(mode == null) return false;


        for(int i = 0 ; i < mode.size() ; i ++){
            ContentValues values = new ContentValues();
            if(!isExistFromSer(mode.get(i).getSerial())){
                //先删除所有往期的试题
//                updateModeState();
                deleteMode();
                deleteEvaluator();
                values.put(EvaluatorDBHelper.MODE_NAME, mode.get(i).getName());
                values.put(EvaluatorDBHelper.MODE_IMAGURL, mode.get(i).getImagePath());
                values.put(EvaluatorDBHelper.MODE_SCORE, mode.get(i).getScore());
                values.put(EvaluatorDBHelper.MODE_SERIAL, mode.get(i).getSerial());
                values.put(EvaluatorDBHelper.MODE_STATE, "1");
                values.put(EvaluatorDBHelper.MODE_EXERCISE_TIME, "0");
                values.put(EvaluatorDBHelper.MODE_UPDATE_TIME, "0");

                SQLiteDatabase db = dbHelper.getWritableDatabase();
                values.put(EvaluatorDBHelper.MODE_TIME, System.currentTimeMillis());
                long index =  db.insert(EvaluatorDBHelper.MODE_TABLE_NAME, null, values);
                if(index < 0){
                    return false;
                }
            }
        }

       return true;
    }

    /**
     * 获取MODE信息
     * @return
     */
    public synchronized List<EvaluatorModeEntity> getEvaluatorMode() {
        List<EvaluatorModeEntity> list = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        EvaluatorModeEntity mode = null;
        if (db.isOpen()) {

            String sql="select * from "+EvaluatorDBHelper.MODE_TABLE_NAME +" where "+EvaluatorDBHelper.MODE_STATE +"=? ";
            Cursor cursor = db.rawQuery(sql, new String[]{"1"});
            while (cursor.moveToNext()) {
                mode = new EvaluatorModeEntity();
                mode.setId(Integer.valueOf(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_ID))));
                mode.setName(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_NAME)));
                mode.setScore(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_SCORE)));
                mode.setImagePath(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_IMAGURL)));
                mode.setSerial(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_SERIAL)));
                mode.setTime(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_TIME)));
                list.add(mode);
            }
            cursor.close();
        }
        return list;
    }

    /**
     * 获取往期MODE信息
     * @return
     */
    public synchronized List<EvaluatorModeEntity> getEvaluatorModeBefore() {
        List<EvaluatorModeEntity> list = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        EvaluatorModeEntity mode = null;
        if (db.isOpen()) {

            String sql="select * from "+EvaluatorDBHelper.MODE_TABLE_NAME +" where "+EvaluatorDBHelper.MODE_STATE +"=? ";
            Cursor cursor = db.rawQuery(sql, new String[]{"0"});
            while (cursor.moveToNext()) {
                mode = new EvaluatorModeEntity();
                mode.setId(Integer.valueOf(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_ID))));
                mode.setName(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_NAME)));
                mode.setScore(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_SCORE)));
                mode.setImagePath(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_IMAGURL)));
                mode.setSerial(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_SERIAL)));
                mode.setTime(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_TIME)));
                list.add(mode);
            }
            cursor.close();
        }
        return list;
    }


    /**
     * 根据serial判断是否存在
     * @return
     */
    public synchronized  boolean isExistFromSer(String ser) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            String sql="select * from "+EvaluatorDBHelper.MODE_TABLE_NAME +" where "+EvaluatorDBHelper.MODE_SERIAL +"=? ";
            Cursor cursor = db.rawQuery(sql, new String[]{ser});
            if(cursor.getCount() > 0){
                cursor.close();
                return true;
            }
            cursor.close();
        }
        return false;
    }

    /**
     * 更新往期试题状态
     */
    public synchronized void updateModeState(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(EvaluatorDBHelper.MODE_STATE, "0");
        db.update(EvaluatorDBHelper.MODE_TABLE_NAME,values," "+EvaluatorDBHelper.MODE_STATE + " = ?",new String[]{"1"});
    }
    /**
     * 更新练习时长，在网络无法上传时使用
     */
    public synchronized void updateExerciseTime(String serial,long time){
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        String sql="select * from "+EvaluatorDBHelper.MODE_TABLE_NAME +" where "+EvaluatorDBHelper.MODE_SERIAL +"=? ";
        Cursor cursor = db.rawQuery(sql, new String[]{serial});
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToNext();
//            String updateTime = cursor.getString(cursor.getColumnIndex(EvaluatorDBHelper.MODE_UPDATE_TIME));
            String allTime = cursor.getString(cursor.getColumnIndex(EvaluatorDBHelper.MODE_EXERCISE_TIME));

//            long updateDay = Long.parseLong(updateTime);
//            String currDay = getFormatDay(System.currentTimeMillis());
//            String upDay = getFormatDay(updateDay);
//            if (upDay.equals(currDay)) {
            time += Long.parseLong(allTime);
//            }
        }
        cursor.close();
        ContentValues values = new ContentValues();
        values.put(EvaluatorDBHelper.MODE_EXERCISE_TIME, ""+time);
        values.put(EvaluatorDBHelper.MODE_UPDATE_TIME, System.currentTimeMillis());
        db.update(EvaluatorDBHelper.MODE_TABLE_NAME,values," "+EvaluatorDBHelper.MODE_SERIAL + " = ?",new String[]{serial});
    }

    /**
     * 清空练习时长
     */
    public synchronized void deleteExerciseTime(String serial){
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(EvaluatorDBHelper.MODE_EXERCISE_TIME, "0");
        values.put(EvaluatorDBHelper.MODE_UPDATE_TIME, System.currentTimeMillis());
        db.update(EvaluatorDBHelper.MODE_TABLE_NAME,values," "+EvaluatorDBHelper.MODE_SERIAL + " = ?",new String[]{serial});
    }

    /**
     * 获取格式化时间
     * @param time
     * @return
     */
    private String getFormatDay(long time){
        if(time < 1)
            return "-1";
        SimpleDateFormat format=new SimpleDateFormat("dd");
        Date d1=new Date(time);
        return format.format(d1);
    }
    /**
     * 获取今日练习时长
     * @return
     */
    public synchronized String getExerciseTime() {
        String time = "0";
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {

            String sql="select * from "+EvaluatorDBHelper.MODE_TABLE_NAME +" where "+EvaluatorDBHelper.MODE_STATE +"=? ";
            Cursor cursor = db.rawQuery(sql, new String[]{"1"});

            while (cursor.moveToNext()) {
                time = cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.MODE_EXERCISE_TIME));
            }
            cursor.close();
        }
        return time;
    }

    /**
     * 更新闯关分数
     * @param score
     */
    public synchronized void updateModeScore(String id, String score){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(EvaluatorDBHelper.MODE_SCORE, score);
        db.update(EvaluatorDBHelper.MODE_TABLE_NAME,values," "+EvaluatorDBHelper.MODE_ID + " = ?",new String[]{id});
    }

    /**
     * 删除全部测评内容信息
     */
    public synchronized void deleteEvaluator(){

        SQLiteDatabase db = dbHelper.getWritableDatabase();

        //先清除上次内容
        db.delete(EvaluatorDBHelper.EVALUATOR_TABLE_NAME,null,null);
    }
    /**
     * 保存测评内容信息
     * @param message
     * @return
     */
    public synchronized boolean insertEvaluator(List<EvaluatorMessageEntity> message){
        if(message == null) return false;
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        for(int i = 0 ; i < message.size() ; i++) {
            ContentValues values = new ContentValues();
            values.put(EvaluatorDBHelper.EVALUATOR_ENGLISH, message.get(i).getEnglish());
            values.put(EvaluatorDBHelper.EVALUATOR_CHINESE, message.get(i).getChinese());
            values.put(EvaluatorDBHelper.EVALUATOR_TYPE, message.get(i).getModetype());
//            values.put(EvaluatorDBHelper.EVALUATOR_SCORE, message.get(i).getScore());
            values.put(EvaluatorDBHelper.EVALUATOR_STATE, message.get(i).getState());
            values.put(EvaluatorDBHelper.EVALUATOR_MODE_SERIAL, message.get(i).getSerial());
            values.put(EvaluatorDBHelper.EVALUATOR_TIME, System.currentTimeMillis());
            values.put(EvaluatorDBHelper.EVALUATOR_MODE_PKSERIAL, message.get(i).getPkSerial());
//            values.put(EvaluatorDBHelper.EVALUATOR_WORD_SCORE, message.get(i).getWordscore());
//            values.put(EvaluatorDBHelper.EVALUATOR_LOCAL_VOICE, message.get(i).getLocalVoicePath());
            long index =  db.insert(EvaluatorDBHelper.EVALUATOR_TABLE_NAME,null,values);
            if(index < 0){
                return false;
            }
        }
        return true;
    }

    /**
     * 获取所有测评试题
     * @return
     */
    public synchronized List<EvaluatorMessageEntity> getEvaluatorMessage(String id) {
        List<EvaluatorMessageEntity> list = new ArrayList<EvaluatorMessageEntity>();
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db.isOpen()) {
            String sql="select * from "+EvaluatorDBHelper.EVALUATOR_TABLE_NAME +" where "+EvaluatorDBHelper.EVALUATOR_MODE_SERIAL +"=? ";
            Cursor cursor = db.rawQuery(sql, new String[]{id});
            while (cursor.moveToNext()) {
                EvaluatorMessageEntity ev = new EvaluatorMessageEntity();
                ev.setId(Integer.valueOf(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_ID))));

                ev.setEnglish(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_ENGLISH)));
                ev.setChinese(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_CHINESE)));
                ev.setModetype(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_TYPE)));
                ev.setScore(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_SCORE)));
                ev.setState(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_STATE)));
                ev.setLocalVoicePath(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_LOCAL_VOICE)));
                ev.setWordscore(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_WORD_SCORE)));
                ev.setSerial(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_MODE_SERIAL)));
                ev.setPkSerial(cursor.getString(cursor
                        .getColumnIndex(EvaluatorDBHelper.EVALUATOR_MODE_PKSERIAL)));
                list.add(ev);
            }
            cursor.close();
        }
        return list;
    }

    /**
     * 整体更新单个测试题信息
     * @param message
     * @return
     */
    public synchronized long updateEvaluator(EvaluatorMessageEntity message){
        if(message == null) return -1;
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
//        values.put(EvaluatorDBHelper.EVALUATOR_ENGLISH, message.getEnglish());
//        values.put(EvaluatorDBHelper.EVALUATOR_CHINESE, message.getChinese());
//        values.put(EvaluatorDBHelper.EVALUATOR_TYPE, message.getModetype());
        values.put(EvaluatorDBHelper.EVALUATOR_SCORE, message.getScore());
        values.put(EvaluatorDBHelper.EVALUATOR_STATE, message.getState());
        values.put(EvaluatorDBHelper.EVALUATOR_WORD_SCORE, message.getWordscore());
        values.put(EvaluatorDBHelper.EVALUATOR_LOCAL_VOICE, message.getLocalVoicePath());
        return db.update(EvaluatorDBHelper.EVALUATOR_TABLE_NAME,values,EvaluatorDBHelper.EVALUATOR_ID+" = ?",new String[]{message.getId()+""});
    }
}